package controllers

import (
	"beego_starter/models"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	"github.com/oldfeel/ofutils"
)

var (
	o  orm.Ormer
	bm cache.Cache
)

func init() {
	bm, _ = cache.NewCache("memory", `{"interval":3600}`)
	o = models.GetOrm()

	var m models.User
	o.QueryTable(m).Filter("Name", "admin").One(&m)
	if m.Id == 0 {
		m.Name = "admin"
		m.Password = ofutils.MD5("admin")
		o.Insert(&m)
	}

	go startTask()
}

type BaseController struct {
	beego.Controller
	U       models.User
	IsLogin bool
	IsAdmin bool
}

func (c *BaseController) Prepare() {
	c.U = c.GetUser()
	if c.U.Id > 0 {
		c.IsLogin = true
	}
}

func (c *BaseController) CheckLogin() bool {
	if !c.IsLogin {
		c.Fail(-1, "请登录")
	}
	return c.IsLogin
}

type MainController struct {
	BaseController
}

func (c *MainController) Get() {
	c.Data["v"] = beego.AppConfig.String("version_code")
	c.TplName = "client/index.html"
}

func (c *MainController) Admin() {
	c.Data["v"] = beego.AppConfig.String("version_code")
	c.TplName = "admin/index.html"
}

func (c *MainController) Upload() {
	if _, err := os.Stat("files"); os.IsNotExist(err) {
		err := os.MkdirAll("files", os.ModePerm)
		if err != nil {
			beego.Error(err)
		}
	}
	f, h, err := c.GetFile("file")
	if err != nil {
		c.Fail(1, err)
		return
	}
	defer f.Close()
	fileName := ofutils.GetTimeStamp() + "_" + ofutils.RandString(8) + filepath.Ext(h.Filename)
	c.SaveToFile("file", "files/"+fileName)
	c.Success(fileName)
}

func (c *MainController) Update() {
	go func() {
		time.Sleep(1 * time.Second)
		cmd := exec.Command("bash", "../restart.sh")
		err := cmd.Run()
		if err != nil {
			beego.Info(err)
		}
	}()
	c.Success("更新成功" + beego.AppConfig.String("version_code"))
}

func (c *BaseController) Fail(code int, data interface{}) {
	var msg string
	switch data.(type) {
	case string:
		msg = data.(string)
	default:
		msg = fmt.Sprint(data)
	}
	c.Data["json"] = map[string]interface{}{"code": code, "data": msg}
	c.ServeJSON()
}

func (c *BaseController) Success(data interface{}) {
	if data == nil {
		data = []string{}
	}
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data}
	c.ServeJSON()
}

func (c *BaseController) EmptyList() {
	c.Success([]string{})
}

func (c *BaseController) Page(data interface{}, qs orm.QuerySeter) {
	total, err := qs.Limit(-1).Offset(0).Count()
	if err != nil {
		c.Fail(2, err)
		return
	}
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data, "total": total}
	c.ServeJSON()
}

func (c *BaseController) Page2(data interface{}, total int) {
	c.Data["json"] = map[string]interface{}{"code": 0, "data": data, "total": total}
	c.ServeJSON()
}

func (c *BaseController) GetUser() (user models.User) {
	token := c.GetString("token")
	if token != "" {
		err := o.QueryTable("User").Filter("Token", token).One(&user)
		if err != nil {
			beego.Info("GetUser", err)
		}
	}
	return user
}
